package com.ubing.boot.notesforjava.utils;


import cn.hutool.core.codec.Base64;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Date;

/**
 * @ClassName : JwtUtils
 * @Description : JwtUtils
 * @Author : ubing
 * @Date: 2023-02-17 10:03
 */
public class JwtUtils {

    public static SecretKey generalKey(){
        //定义密钥
        String secret = "ubing"+"md5";// MD5加密
        //base64编码密钥
        byte[] encode = Base64.encode(secret).getBytes();
        //返回AES加密后的密钥
        return new SecretKeySpec(encode,0,encode.length,"AES");

    }

    //创建token
    public static String createJWT(final String id,final String subject,final long expireMills){
       //定义加密算法
        SignatureAlgorithm hs256 = SignatureAlgorithm.HS256;
        //定义生成签名的密钥
        SecretKey secretKey = generalKey();
        // 借助三方依赖组件jwt的api来实现
        Date now = new Date();
        JwtBuilder builder= Jwts.builder()
                //用户id
                .setId(id)
                //主题
                .setSubject(subject)
                //签发人
                .setIssuer("ubing")
                //签发时间
                .setIssuedAt(now)
                //签发时 指定加密算法和密钥
                .signWith(hs256,secretKey)
                .claim("ss","牛逼");

        //设定过期时间
        if(expireMills>=0){
            long realMills= System.currentTimeMillis()+ expireMills;
            builder.setExpiration(new Date(realMills));
        }
        return builder.compact();
    }
}
